<?php
//截取干净字符串
function getSubStrEllipsis($str, $len=62, $suffix=' ...', $enc='utf-8')
{
    $str = trim(strip_tags($str));
    $str = str_replace(array("\r\n", "\r", "\n"), '', $str);
    $str = preg_replace('/\s(?=\s)/', '', $str);
    if(mb_strlen($str, $enc) <= $len){ return $str; }
    $str = mb_substr($str, 0, $len, $enc);
    return $str.$suffix;
}

//把字符串变换成seo格式
function the_seo_filter($string, $limit=1)
{
    $retval = $string;
    $pattern = '/[\p{P}\p{S}]/u';
    $pattern_letter = '/[!"#$%&\'()*+,.\/:;<=>?@[\\\]^_`{|}~]/';
    $retval = preg_replace($pattern, '', strtolower($retval));
    $retval = preg_replace($pattern_letter, '', $retval);
    $retval = preg_replace('/\s/', '-', $retval);
    $foo = explode('-', $retval);
    foreach($foo as $value){
        switch (true){
            case ( strlen($value) <= $limit ):
                continue;
            default:
                $container[] = $value;
                break;
        }
    }
    $container = ( sizeof($container) > 0 ? implode('-', $container) : $string );
    return $container;
}

//得到一个网址的主域名
function getUrlDomain($url='')
{
    $url = trim($url); if($url == ''){ return false; }
    $pieces = parse_url($url);
    $domain = isset($pieces['host']) ? $pieces['host'] : '';
    if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
        return $regs['domain'];
    }
    return false;
}

//自定义加密函数
function my_encode($str)
{
    return md5($str.'_panda');
}
function xr_encode($str)
{
    return my_encode($str);
}

//获取文件夹中的文件列表
function getDirFile($dir, $pre='')
{
    $dir = $_SERVER['DOCUMENT_ROOT'].$dir;
    $fileArray = array();
    if(is_dir($dir)){

        if (false != ($handle = opendir($dir)))
        {
            $i=0;
            while ( false !== ($file = readdir($handle)) )
            {
                //去掉"“.”、“..”以及带“.xxx”后缀的文件
                if ($file!="." && $file!=".." && strpos($file,"."))
                {
                    $fileArray[$i] = $pre.$file;
                    $i++;
                }
            }
            //关闭句柄
            closedir( $handle );
        }
    }
    return $fileArray;
}

//把xml文件解析成数组
function _xmlToArray($file, $type=false, $returnArray=true)
{
    $file = trim($file);
    if($type){
        if(!is_file($file)){return null;}
        $str = simplexml_load_file($file);
    }else{
        if($file == ''){return null;}
        $str = simplexml_load_string($file);
    }
    return json_decode(json_encode($str), $returnArray);
}

/**
 * 对查询结果集进行排序
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param string $sortby 排序类型 asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby='asc')
{
    if(is_array($list)){
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ( $refer as $key=> $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }
    return false;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pk
 * @param string $pid parent标记字段
 * @param string $child 子数组标记
 * @param int $root
 * @return array
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 */
function tree_to_list($tree, $child = '_child', $order='id', &$list = array())
{
    if(is_array($tree)) {
        $refer = array();
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if(isset($reffer[$child])){
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby='asc');
    }
    return $list;
}

/**
 * 把多维数组转化成一维数组
 *
 * @param array $arr 需要转换的数组，必须有相同的子节点
 * @param string $sub 子节点名称
 * @param array &$rs 返回的引用数组
 *
 * @return array
 */
function floatArray($arr=array(), $sub='_sub', &$rs)
{
    if(empty($arr)){ return false; }
    foreach($arr as $v){
        $tmp2 = $v;
        if(isset($tmp2[$sub])){
            unset($tmp2[$sub]);
            $rs[] = $tmp2;
            floatArray($v[$sub], $sub, $rs);
        }else{
            $rs[] = $v;
        }
    }
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function formatBytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/*调试输出*/
function ddd($var, $exit=false, $printr=false)
{
    if($printr){
        echo '<pre>';print_r($var);echo '</pre>';
    }else{
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if(!extension_loaded('xdebug')){
            $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
            $output = '<pre>'. htmlspecialchars($output, ENT_QUOTES).'</pre>';
        }
        echo $output;
    }
    if ($exit){exit;}
    else{return;}
}

//_mkDir
function _mkDir($dir, $mode=0777)
{
    if (!is_dir($dir)) {
        _mkDir(dirname($dir), $mode);
        $old = umask(0);
        @mkdir($dir, $mode);
        umask($old);
        return true;
    }
    return true;
}

//_delDir
function _rmDir($dir)
{
    if( ! is_dir($dir)){ return false; }
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if($file!="." && $file!=".."){
            $fullpath = $dir."/".$file;
            if(!is_dir($fullpath)){unlink($fullpath);}
            else{rmdir($fullpath);}
        }
    }
    closedir($dh);
    if(rmdir($dir)){return true;}
    else{return false;}
}

//会员是否登录
function is_member_login()
{
    $a = cdSession('member_id');
    return empty($a) ? 0 : $a;
}

//判断是否为email
function isEmail($str)
{
    return (filter_var($str, FILTER_VALIDATE_EMAIL) === false) ? false : true;
}

//随机字符
function _randStr($len=6, $type=3, $addChars=null){
    $str = '';
    switch($type) {
        case 1:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 2:
            $chars = str_repeat('0123456789',3);
            break;
        case 3:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
            break;
        case 4:
            $chars = 'abcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        default :
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
            break;
    }
    if($len>10){$len = 10;}
    $charLen = strlen($chars) - 1;
    for($i=0; $i<$len; $i++){
        $str .= $chars[mt_rand(0, $charLen)];
    }
    return $str;
}

//过滤输出数据库数据
function Out($data, $filters='stripslashes')
{
    $filters = explode(',', $filters);
    foreach($filters as $filter){
        if(function_exists($filter)) {
            $data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data);
        }
    }
    return $data;
}

//过滤输出数据库数据
function In($data, $filters='addslashes')
{
    $filters = explode(',', $filters);
    foreach($filters as $filter){
        if(function_exists($filter)) {
            $data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data);
        }
    }
    return $data;
}

//得到评论星级
function getReviewStarLevel($times=0, $stars=0)
{
    $times = intval($times);
    $stars = intval($stars);
    if($times<1 || $stars<1){ return array('a'=>0, 'b'=>0); }
    $a = intval($stars/$times);
    $b = (($stars%$times) == 0) ? 0 : 5;
    if($a > 5){ $a = 5; $b = 0; }
    return array('a'=>$a, 'b'=>$b);
}

//多个<br>化成一个
function merge_brs($string)
{
    $string = str_replace(array("\r\n", "\r", "\n"), '', $string);
    return preg_replace("/(<br\s?\/?>\s?)+/i", "<br/>", $string);
}

//把 n 换成 <br>
function nl_to_br($string, $only=true)
{
    $string = str_replace(array("\r\n", "\r", "\n"), '<br/>', $string);
    if($only){
        return preg_replace("/(<br\s?\/?>\s?)+/i", "<br/>", $string);
    }else{
        return $string;
    }
}

//文件后缀名
function fileExt($filename, $scope=10)
{
    return strtolower(trim(substr(strrchr($filename, '.'), 1, $scope)));
}

//得到表名称
function getTable($t = '')
{
    return \Common\Base\TablesBase::getTableName($t);
}

//管理员是否登录
function is_adm_login()
{
    $a = session('admin_id');
    return empty($a) ? 0 : session('admin_id');
}

//得到一个商品seo过的url
function getGoodsSeoUrl($goods_id=0, $goods_name='', $prefix=true, $suffix='.html')
{
    $goods_id = intval($goods_id); if($goods_id < 1){ return ''; }
    $goods_name = trim($goods_name); if($goods_name == ''){ return ''; }
    return ($prefix?C('HTTP_SERVER'):'').the_seo_filter($goods_name, 0).'-p-'.$goods_id.$suffix;
}

//得到一个分类seo过的url
function getCategorySeoUrl($category_id=0, $category_name='', $prefix=true, $suffix='.html')
{
    $category_id = intval($category_id); if($category_id < 1){ return ''; }
    $category_name = trim($category_name); if($category_name == ''){ return ''; }
    return ($prefix?C('HTTP_SERVER'):'').the_seo_filter($category_name).'-c-'.$category_id.$suffix;
}

//得到一个条款seo过的url
function getClauseSeoUrl($page_id=0, $page_name='')
{
    $page_id = intval($page_id); if($page_id < 1){ return ''; }
    $page_name = trim($page_name); if($page_name == ''){ return ''; }
    return C('HTTP_SERVER').the_seo_filter($page_name).'-i-'.$page_id.'.html';
}

//得到一个 daily 的 url
function getDailySeoUrl($timestamp='')
{
    $timestamp = trim($timestamp);
    if($timestamp == ''){ $timestamp = date('Y-m-d'); }
    return C('HTTP_SERVER').'daily/'.$timestamp;
}

//夸子域名：存储登录信息(home,mobile,cps,blog等等)
function cdSession($name=null, $value='')
{
    $space = 'CD'; //cross domains 跨子域名
    if($name === ''){//没有key
        return null;
    }
    if(is_null($name)){//清空
        unset($_SESSION[$space]);
    }else{
        if($value === ''){//取值
            return isset($_SESSION[$space][$name]) ? $_SESSION[$space][$name] : null;
        }elseif($value === null) {//销毁变量
            unset($_SESSION[$space][$name]);
        }else{//赋值
            $_SESSION[$space][$name] = $value;
        }
    }
    return null;
}

//夸子域名：存储登录信息(home,mobile,cps,blog等等)
function cdCookie($name='', $value='', $option=null)
{
    // 默认设置
    $config = array(
        'prefix'    =>  'cd_', // cookie 名称前缀
        'expire'    =>  C('COOKIE_EXPIRE'), // cookie 保存时间
        'path'      =>  C('COOKIE_PATH'), // cookie 保存路径
        'domain'    =>  C('COOKIE_DOMAIN'), // cookie 有效域名
        'httponly'  =>  C('COOKIE_HTTPONLY'), // httponly设置
    );
    // 参数设置(会覆盖黙认设置)
    if (!is_null($option)) {
        if (is_numeric($option))
            $option = array('expire' => $option);
        elseif (is_string($option))
            parse_str($option, $option);
        $config     = array_merge($config, array_change_key_case($option));
    }
    if(!empty($config['httponly'])){
        ini_set("session.cookie_httponly", 1);
    }
    // 清除指定前缀的所有cookie
    if (is_null($name)) {
        if (empty($_COOKIE))
            return;
        // 要删除的cookie前缀，不指定则删除config设置的指定前缀
        $prefix = empty($value) ? $config['prefix'] : $value;
        if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
            foreach ($_COOKIE as $key => $val) {
                if (0 === stripos($key, $prefix)) {
                    setcookie($key, '', time() - 3600, $config['path'], $config['domain']);
                    unset($_COOKIE[$key]);
                }
            }
        }
        return;
    }elseif('' === $name){
        // 获取全部的cookie
        return $_COOKIE;
    }
    $name = $config['prefix'] . str_replace('.', '_', $name);
    if ('' === $value) {
        if(isset($_COOKIE[$name])){
            $value =    $_COOKIE[$name];
            if(0===strpos($value,'think:')){
                $value  =   substr($value,6);
                return array_map('urldecode',json_decode(MAGIC_QUOTES_GPC?stripslashes($value):$value,true));
            }else{
                return $value;
            }
        }else{
            return null;
        }
    } else {
        if (is_null($value)) {
            setcookie($name, '', time() - 3600, $config['path'], $config['domain']);
            unset($_COOKIE[$name]); // 删除指定cookie
        } else {
            // 设置cookie
            if(is_array($value)){
                $value  = 'think:'.json_encode(array_map('urlencode',$value));
            }
            $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
            setcookie($name, $value, $expire, $config['path'], $config['domain']);
            $_COOKIE[$name] = $value;
        }
    }
}

//生成 10 位的优惠券编号
function genCouponSN($member_id = 0)
{
    $member_id = intval($member_id); if($member_id < 1){ return null; }
    $dic = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
    return 'C'.substr('00'.$member_id, -4).substr($dic, 0, 5);
}

//由 member_id 取得 avatar 的地址
function getMemberAvatar($member_id=0, $ext='jpg', $type='dir')
{
    $member_id = intval($member_id);
    if($member_id < 1){ $member_id = 1; }
    if($type === 'pic'){
        return 'a'.intval($member_id/1000).'/avatar_'.$member_id.'.'.$ext;
    }else{
        return 'a'.intval($member_id/1000).'/';
    }
}

//得到分页大小
function getPageSize()
{
    $sz = session('page_size');
    if(empty($sz)){
        session('page_size', 20);
        $sz = 20;
    }
    return $sz;
}

//得到商品排序方式
function getSortBy()
{
    /*s1,s2,s3,s4在PublicController.class.php中也对应存在，要记得同时修改*/
    $sort_by = session('sort_by'); if(empty($sort_by)){ $sort_by = 's1'; session('sort_by', 's1'); }
    $str = '';
    switch($sort_by){
        case 's1':
            $str = ' id desc ';
            break;
        case 's2':
            $str = ' sold desc ';
            break;
        case 's3':
            $str = ' price desc ';
            break;
        case 's4':
            $str = ' price asc ';
            break;
        default:
            ;
    }
    return $str;
}

//保留两位小数。如18.0000会得到string(18.00)；而round会得到float(18)
function _round($float, $n=2)
{
    return number_format($float, $n);
}

//得到优惠百分比
function getPrivilegePricePercent($price=0.0, $price_s=0.0, $jd=0)
{
    $price = floatval($price);if($price < 0.0){ return 0; }
    $price_s = floatval($price_s);if($price_s < 0.0){ return 0; }
    if($price_s >= $price){
        return 0;
    }else{
        return round((($price-$price_s)/$price)*100, $jd);
    }
}

//多久以前
function xTimeAgo($ts = 0)
{
    $ts = intval($ts); if($ts < 1){ return null; }
    $now_ts = time(); if($ts > $now_ts){ return null; }
    $cha = $now_ts - $ts;
    if($cha < 3600){
        //分钟
        return intval($cha/60).' minutes ago';
    }elseif($cha>=3600 && $cha<86400){
        //小时
        return intval($cha/3600).' hours ago';
    }elseif($cha>=86400 && $cha<604800){
        //天
        return intval($cha/86400).' days ago';
    }elseif($cha>=604800 && $cha<2419200){
        //星期
        return intval($cha/604800).' weeks ago';
    }elseif($cha>=2419200 && $cha<31536000){
        //月
        return intval($cha/2419200).' months ago';
    }else{
        //年
        return intval($cha/31536000).' years ago';
    }
}

//得到当前货币代码
function getNowCurrency()
{
    $home_model_currency = new \Home\Model\CurrencyModel();
    return $home_model_currency->getNowCurrency();
}

//得到购物车中商品数量
function getCartGoodsCount()
{
    $m_cart = new \Home\Model\CartModel();
    $mid = is_member_login();
    if($mid > 0){
        $cart = $m_cart->getDbCartByMemberID($mid);
    }else{
        $cart = $m_cart->getCookieCart();
    }
    if(empty($cart)){ return 0; }
    else{
        $ct = 0;
        foreach($cart as $c){
            $ct += $c['amt'];
        }
        return $ct;
    }
}

/**
 * Curl 发送POST请求
 *
 * @param string $url
 * @param array $req
 *
 * @return mixed
 */
function xrCurl($url, $req=array())
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    if( ! empty($req)){
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($req));
    }
    $res = curl_exec($ch);
    return $res;
}

//得到 Goods_daily
function getGoodsDaily($n=12, $cache=true)
{
    if($n < 1){ return array(date('Y-m-d')); }
    if($cache){
        $rt = S(C('daily_cache').$n);
        if($rt !== false){
            return $rt;
        }
    }
    $m_daily = new \Home\Model\DailyModel();
    $rs = $m_daily->getGoodsDaily($n);
    if(empty($rs)){
        return array(date('Y-m-d'));
    }else{
        $rt = array();
        foreach($rs as $v){
            $rt[] = $v['d_a'];
        }
        if($cache){
            S(C('daily_cache').$n, $rt, C('daily_cache_gc'));
        }
        return $rt;
    }
}

//得到照片seo的url
function getPhotoSeoUrl($id=0, $photo_name='', $prefix=true, $suffix='.html')
{
    $id = intval($id); if($id < 1){ return ''; }
    $photo_name = trim($photo_name);
    return ($prefix?C('HTTP_SERVER'):'').the_seo_filter($photo_name, 0).'-photo-'.$id.$suffix;
}